package com.daykw.xiaohongshu.task;

import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.stereotype.Service;

import com.daykw.xiaohongshu.model.TKeywordTask;
import com.daykw.xiaohongshu.task.thread.KeywordJobThread;
import com.daykw.xiaohongshu.util.Const;
import com.daykw.xiaohongshu.util.QuartzManager;
import com.daykw.xiaohongshu.util.SpringContextHolder;

@DisallowConcurrentExecution
@Service
public class KeywordJob extends CustmTask {

	private static Logger logger = Logger.getLogger(KeywordJob.class);

	public void doStart() {
		logger.info("初始化获取LiajiaJobs任务...");
		try {
			if (QuartzManager.getTrigger("KeywordJob") == null) {
				QuartzManager.addJob("KeywordJob", this, "0/5 * * * * ?");
			} else {
				logger.info("已经存在任务:Jobs");
			}
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	@Override
	public void doWork() {
		try {
			if (SpringContextHolder.getApplicationContext() == null) {
				try {
					TimeUnit.SECONDS.sleep(3);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				logger.info("等待上下文启动");
			}
			if (Const.PAGE_THREAD > 0) {
				NutDao dao = SpringContextHolder.getBean("dao");
				ExecutorService pool = this.getPool(Const.PAGE_THREAD);
				int node = new Random().nextInt(10);
				List<TKeywordTask> list = dao.query(TKeywordTask.class,
						Cnd.where("status", "=", 0).and("node", "=", node).limit(1, Const.PAGE_THREAD));
				// String[] ips = this.getIps();
				for (TKeywordTask task : list) {
					Thread thread = new Thread(new KeywordJobThread(task));
					try {
						pool.execute(thread);
						Thread.sleep(10);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
